import { Box, Button, Paper, TextField } from "@mui/material";
import { useSnackbar } from "notistack/dist";
import React, { useEffect, useRef, useState } from "react";
import MyButton from "../../components/MyButton";
import RandomButton from "../../components/RandomButton";
import "./BoxSort.css";
import MyBox from "./MyBox";
import Mycard from "./Mycard";

export default function BoxSort(props) {
  const [ipt, setIpt] = useState();
  const [box, setBox] = useState([]);
  const [posx, setPosx] = useState([]);
  const [posy, setPosy] = useState([]);
  const [numbers, setNumbers] = useState([]);
  const [isSorting, setIsSorting] = useState(false);
  const { enqueueSnackbar } = useSnackbar();
  const { msg, setMsg } = props;
  var pos = [],
    cnt = [],
    len,
    tmsg = msg;
  const mount = useRef(false);
  const change = async () => {
    if (isSorting) {
      enqueueSnackbar("正在排序", { variant: "warning" });
      return;
    }
    if (ipt == null) {
      enqueueSnackbar("请输入以英文逗号分隔的正整数", { variant: "error" });
      return;
    }
    var arr = ipt.split(",").map((val) => +val);
    for (var i in arr) {
      if (isNaN(arr[i]) || arr[i] == 0) {
        enqueueSnackbar("请输入以英文逗号分隔的正整数", { variant: "error" });
        return;
      }
    }
    setIsSorting(true);
    setNumbers(arr);
    len = arr.length;
    tmsg = { ...msg, cT: 0, sT: 0, tot: len };
    if (mount.current) setMsg({ ...tmsg });
    else return;

    await solve(arr);
    setIsSorting(false);
  };
  const sleep = (time) => {
    return new Promise(function (resolve) {
      setTimeout(resolve, time * props.speed);
    });
  };

  useEffect(() => {
    setMsg({
      sentence: "箱子排序",
      sT: 0,
      cT: 0,
      tot: 0,
    });
    mount.current = true;
    return () => (mount.current = false);
  }, []);

  const solve = async (arr) => {
    var sar = [...arr];
    cnt = [];
    for (var i in sar) {
      for (var j = 0; j < len - i - 1; ++j) {
        if (sar[j] > sar[j + 1]) {
          // console.log(j);
          var tt = sar[j];
          sar[j] = sar[j + 1];
          sar[j + 1] = tt;
        }
      }
    }

    var nl = 1;
    pos[sar[0]] = 0;
    cnt[sar[0]] = 0;
    for (var i = 1; i < len; ++i) {
      if (sar[i] !== sar[i - 1]) {
        // console.log(i);
        sar[nl] = sar[i];
        cnt[sar[i]] = 0;
        pos[sar[i]] = nl++;
      }
    }

    sar = sar.slice(0, nl);

    // console.log(pos);

    setBox([...sar]);

    await sleep(500);

    var tposx = [],
      tposy = [];
    for (var i = 0; i < len; ++i) {
      tposx[i] = i;
      tposy[i] = -350;
    }

    setPosx([...tposx]);
    setPosy([...tposy]);

    await sleep(1000);

    // console.log(cnt);

    for (var i = 0; i < len; ++i) {
      tposx[i] = pos[arr[i]];
      // console.log(numbers[i], pos[numbers[i]]);
      tposy[i] = -40 * cnt[arr[i]];
      cnt[arr[i]]++;

      tmsg = { ...tmsg, sT: tmsg.sT + 1, sentence: arr[i] + "放入箱子" };
      if (mount.current) setMsg({ ...tmsg });
      else return;
      setPosx([...tposx]);
      setPosy([...tposy]);

      await sleep(500);
    }

    // console.log(tposx, tposy);
    var tlen = len - 1;
    for (var i = nl - 1; i >= 0; --i) {
      for (var j = len - 1; j >= 0; --j) {
        if (arr[j] == sar[i]) {
          tposx[j] = tlen--;
          tposy[j] = -350;
          tmsg = { ...tmsg, sT: tmsg.sT + 1, sentence: "取出" + sar[i] };

          if (mount.current) setMsg({ ...tmsg });
          else return;

          setPosx([...tposx]);
          setPosy([...tposy]);

          await sleep(500);
        }
      }
    }
  };
  return (
    <Paper className="mybody" elevation={3}>
      <div className="Inner">
        {box.map((val, index) => {
          return <MyBox number={val} pos={index} />;
        })}
        {posx.map((val, index) => (
          <Mycard number={numbers[index]} posx={val} posy={posy[index]} />
        ))}
      </div>
      <div
        style={{
          width: "100%",
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
          marginTop: "20px",
        }}
      >
        <TextField
          // label="数据"
          value={ipt}
          size="small"
          helperText="*请输入英文逗号隔开的正整数"
          onChange={(e) => {
            setIpt(e.target.value);
          }}
        />
        <Box sx={{ marginTop: 4, display: "flex", flexDirection: "row" }}>
          <MyButton loading={isSorting} variant="contained" onClick={change}>
            {isSorting ? "正在排序" : "提交"}
          </MyButton>
          <RandomButton setData={setIpt} loading={isSorting}></RandomButton>
        </Box>
      </div>
    </Paper>
  );
}
